package model

import (
	"errors"
	"log"
	"time"
)

type UserInfoModel struct {
	Uid         uint64    `gorm:"column:uid;primary_key" json:"uid"`
	UserName    string    `gorm:"column:user_name;not null" json:"username"`
	PhoneNumber string    `gorm:"column:phone_number;not null" json:"phonenumber" binding:"required" form:"phonenumber"`
	Sex         string    `gorm:"column:sex;not null" json:"sex" binding:"required" form:"sex"`
	Address     string    `gorm:"column:address;not null" json:"address"`
	Email       string    `gorm:"column:email;not null" json:"email" binding:"required" form:"email"`
	CreateAt    time.Time `gorm:"column:created_at" json:"create_at"`
	//关联字段
	Posts []Post `gorm:"foreignkey:UserId"  binding:"-"`
}

// 通过传入的作者查询文章
func (a *UserModel) GetPostByUser() error {
	return DB.Self.Preload("Posts").First(&a).Error
}

// 根据用户uid查询用户信息
func GetUserInfoByUid(uid uint64) (*UserInfoModel, error) {
	u := &UserInfoModel{}
	if r := DB.Self.Where("uid=?", uid).First(&u).Error; r != nil {
		return nil, errors.New("no such user")
	}
	return u, nil
}

// 根据用户uid查post
func GetPostByUid(uid uint64) (*[]Post, error) {
	//p := &Post{}
	//r := DB.Self.Where("uid=?", uid).Preload("Writer").Find(&p)
	//return p, r.Error
	var posts []Post
	result := DB.Self.Where("uid = ?", uid).Preload("Writer").Find(&posts)

	if result.Error != nil {
		log.Printf("Database query failed: %v", result.Error)
		return nil, result.Error
	}

	if len(posts) == 0 {
		return nil, errors.New("no posts found for the given user ID")
	}

	return &posts, nil
}
